package middleware

import (
	"context"
	"errors"
	"os"
	"time"

	jwtModel "pay_service/biz/model/jwt"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/hertz-contrib/jwt"
)

const (
	JWTIdentityKey    = "identity"
	JWTidentityUserID = "identity_user_id"
)

var JWTMiddleware *jwt.HertzJWTMiddleware

func InitJWT() error {
	if JWTMiddleware != nil {
		return nil
	}
	secretKey := os.Getenv("JWT_SECRET_KEY")
	if secretKey == "" {
		return errors.New("get secret key errors")
	}
	authMiddleware, err := jwt.New(&jwt.HertzJWTMiddleware{
    Realm:         "test zone", // TODO: may need to change it, but now keep as same as user service
		Key:           []byte(secretKey),
		Timeout:       time.Hour,
		MaxRefresh:    time.Hour,
		TokenLookup:   "header: Authorization, query: token, cookie: jwt",
		TokenHeadName: "Bearer",
		IdentityKey:   JWTIdentityKey,
    // will store the return value to app RequestContext
		IdentityHandler: func(ctx context.Context, c *app.RequestContext) interface{} {
			claims := jwt.ExtractClaims(ctx, c)
			return &jwtModel.JWTUser{
				UserName: claims[JWTIdentityKey].(string),
				UserID:   claims[JWTidentityUserID].(int64),
			}
		},
	})
	if err != nil {
		return err
	}
	JWTMiddleware = authMiddleware
	return nil
}
